package com.boot.security.server.controller.mffl.MfflContract;

import com.boot.security.server.dao.mffl.MfflContractDao;
import com.boot.security.server.dao.mffl.MfflTypeDao;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.MfflContract;
import com.boot.security.server.model.mffl.Vo.MfflContractVo;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.impl.mffl.MfflContract.MfflContractService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.MfflUser.mfflUserService;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同服务（用户端）
 */
@RestController
@RequestMapping("/client/mfflContracts")
@Api(tags = "合同服务（用户端）")
public class Cilent_MfflContractController {

    //合同dao
    @Autowired
    private MfflContractDao mfflContractDao;

    //合同service
    @Autowired
    MfflContractService mfflContractservice;

    //服务类型
    @Autowired
    MfflTypeDao mffltypedao;

    @Autowired
    mfflUserService mffluserservice;

    //微信支付
    @Autowired
    WXPayService wxPayService;

    //推送
    @Autowired
    private com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl MfflSystemMessagesImpl;

    //公共功能
    @Autowired
    private com.boot.security.server.service.impl.mffl.Mfflpublic.publicService publicService;

    @ApiOperation(value = "合同定制/合同审核---发布")
    @PostMapping
    public ReturnBean save(@ApiParam(name = "serviceId", value = "服务id(0合同定制，1合同审核)", required = true) @RequestParam Integer serviceId,
                           @ApiParam(name = "typeId", value = "服务类型id", required = true) @RequestParam Integer typeId,
                           @ApiParam(name = "email", value = "收件邮箱", required = true) @RequestParam String email,
                           @ApiParam(name = "content", value = "备注") @RequestParam(required = false) String content,
                           @ApiParam(name = "imageUrl", value = "图片地址(按照分号分割)") @RequestParam(required = false) String imageUrl,
                           @ApiParam(name = "serviceLawyerId", value = "服务律师id", required = true) @RequestParam Integer serviceLawyerId) {

        if (serviceId == null) {
            return new ReturnBean("201", "服务id,不能为空");
        }
        if (typeId == null) {
            return new ReturnBean("201", "服务类型id,不能为空");
        }
        if (StringUtils.isEmpty(email)) {
            return new ReturnBean("201", "收件邮箱,不能为空");
        }
        if (serviceLawyerId == null) {
            return new ReturnBean("201", "服务律师id,不能为空");
        }
        //mfflContractDao.save(mfflContract);
        try {
            return mfflContractservice.contractSave(serviceId, typeId, email, content, imageUrl, serviceLawyerId);
        } catch (Exception e) {
            e.printStackTrace();
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("105");
            return returnBean;
        }
    }


    @PostMapping(value = "pay")
    @ApiOperation(value = "支付")
    public ReturnBean pay(@ApiParam(name = "paymerchantnumber", value = "支付订单号", required = true) @RequestParam String paymerchantnumber) {
        if (StringUtils.isEmpty(paymerchantnumber)) {
            return new ReturnBean("paymerchantnumber不能为空", "201");
        }
        ReturnBean returnBean = mfflContractservice.ServicePay(paymerchantnumber, "/client/mfflContracts/wechatpaycallback");
        return returnBean;
    }

    /**
     * 微信回调数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ApiIgnore
    @RequestMapping(value = "wechatpaycallback")
    @ResponseBody
    @Transactional
    public String WechatPayCallback(HttpServletRequest request) throws Exception {
        //处理微信回调数据
        Map<String, String> returnmap = wxPayService.WechatPayCallback(request);

        //修改订单信息
        boolean b = mfflContractservice.WechatPayCallback(returnmap);

        //微信回调数据
        return wxPayService.WechatPayCallbackReturnData(b);
    }

    /**
     * 用户拨打律师电话
     *
     * @param id
     * @return
     */
    @GetMapping(value = "Phone")
    @ApiOperation("用户拨打律师电话")
    public ReturnBean Phone(@ApiParam(name = "id", value = "合同id", required = true) @RequestParam Integer id) {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        return mfflContractservice.Phone(1, id);
    }

    /**
     * 用户确认完成
     *
     * @param id
     * @return
     */
    @PostMapping(value = "ConfirmCompletion")
    @ApiOperation(value = "用户确认完成")
    public ReturnBean ConfirmCompletion(@ApiParam(name = "id", value = "合同id", required = true) @RequestParam Integer id,
                                        @ApiParam(name = "comment", value = "评论内容", required = true) @RequestParam String comment,
                                        @ApiParam(name = "rank", value = "评论级别 1好评 2中评 3差评", required = true) @RequestParam Integer rank) {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        if (StringUtils.isEmpty(comment)) {
            return new ReturnBean("201", "评论内容不能为空");
        }
        if (rank == null) {
            return new ReturnBean("201", "评论级别不能为空");
        }
        if (rank < 0 && rank > 3) {
            return new ReturnBean("201", "评论级别不得小于0,或大于3");
        }
        ReturnBean returnbean = null;
        try {
            returnbean = mfflContractservice.comment(comment, rank, id);
            returnbean = mfflContractservice.ConfirmCompletion(id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return returnbean;
        }
    }


    /**
     * 按id获取合同
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "按id获取合同")
    public ReturnBean<MfflContractVo> get(@ApiParam(name = "id", value = "合同id", required = true) @PathVariable Integer id) {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        return mfflContractservice.getIdlawyerletter(id);
    }


    /**
     * 列表
     *
     * @param request
     * @return
     */
    @GetMapping
    @ApiOperation(value = "列表")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "serviceId", value = "4合同审核，5合同定制,不传获取全部", paramType = "query", dataType = "int")})
    public ReturnBean<MfflContract> list(PageTableRequest request) {
        if (request.getOffset() == null) {
            return new ReturnBean("201", "offset不能为空");
        }
        if (request.getLimit() == null) {
            return new ReturnBean("201", "limit不能为空");
        }

        //查询当前用户的
        SysUser sysUser = UserUtil.getLoginUser();
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid", sysUser.getId());
        map.put("serviceId", request.getParams().get("serviceId"));
        map.put("deleteState", 1);
        request.setParams(map);

        PageTableResponse handle = new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return mfflContractDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<MfflContract> list(PageTableRequest request) {
                return mfflContractDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);

        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(handle);

        return returnBean;
    }


    @DeleteMapping("/cancel")
    @ApiOperation(value = "取消发布")
    public ReturnBean cancel(@ApiParam(name = "id", value = "合同id", required = true) @RequestParam Long id) throws Exception {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        return mfflContractservice.cancelLawyerletter(id);
    }

    @GetMapping("refund")
    @ApiOperation(value = "申请退款")
    public ReturnBean refund(@ApiParam(name = "id", value = "合同id", required = true) @RequestParam Long id,
                             @ApiParam(name = "refundreason", value = "退款原因", required = true) @RequestParam String refundreason) {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        if (StringUtils.isEmpty(refundreason)) {
            return new ReturnBean("201", "退款原因不能为空");
        }
        try {
            return mfflContractservice.refund(id, refundreason);
        } catch (Exception e) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("105");
            return returnBean;
        }

    }

    @GetMapping("cancelRefund")
    @ApiOperation(value = "取消退款")
    public ReturnBean cancelRefund(@ApiParam(name = "id", value = "合同id", required = true) @RequestParam Long id) {
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        try {
            return mfflContractservice.cancelRefund(id);
        } catch (Exception e) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("105");
            return returnBean;
        }
    }

    @PostMapping("orderquery")
    @ApiOperation(value = "查询订单状态，在确认用户完成支付后调用。（不信任回调函数）)")
    public ReturnBean orderquery(@ApiParam(name = "payMerchantNumber", value = "商户订单号", required = true) @RequestParam String payMerchantNumber) throws Exception {
        if (StringUtils.isEmpty(payMerchantNumber)) {
            return new ReturnBean("201", "paymerchantnumber不能为空");
        }
        return mfflContractservice.orderquery(payMerchantNumber);
    }

  /*  @GetMapping("getsrvicelaywer")
    @ApiOperation("获取合同服务的律师")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int")})
    public ReturnBean getServiceLaywer(PageTableRequest reques, @ApiParam(name = "service", value = "合同类型（0合同审核，1合同定制）", required = true) @RequestParam Integer service) {
        if (reques.getOffset() == null) {
            return new ReturnBean("201", "offset不能为空");
        }
        if (reques.getLimit() == null) {
            return new ReturnBean("201", "limit不能为空");
        }
        if (service == null) {
            return new ReturnBean("201", "合同类型不能为空");
        }
        return mffluserservice.getServiceLawyer(reques, service == 0 ? 4 : 5);
    }*/


   /* @PostMapping("comment")
    @ApiOperation("评价")
    public ReturnBean comment(@ApiParam(name = "comment", value = "评论内容", required = true) @RequestParam String comment,
                              @ApiParam(name = "rank", value = "评论级别 1好评 2中评 3差评", required = true) @RequestParam Integer rank,
                              @ApiParam(name = "id", value = "合同id", required = true) @RequestParam Integer id) {
        if (StringUtils.isEmpty(comment)) {
            return new ReturnBean("201", "评论内容不能为空");
        }
        if (rank == null) {
            return new ReturnBean("201", "评论级别不能为空");
        }
        if (rank > 0 && rank < 3) {
            return new ReturnBean("201", "评论数字不得小于0,或大于3");
        }
        if (id == null) {
            return new ReturnBean("201", "合同id不能为空");
        }
        return mfflContractservice.comment(comment, rank, id);
    }*/

  /*  @GetMapping("test")
    public ReturnBean test(){
        ReturnBean returnBean = new ReturnBean("200","");
        HashMap<String, String> map = new HashMap<>();
        String str = ProjectUtil.payMerchantNumber();
        map.put("data",str);
        map.put("length",String.valueOf(str.length()));
        returnBean.setDatas(map);
        return returnBean;
    }*/
   /*
    @PutMapping
    @ApiOperation(value = "修改")
    public MfflContract update(@RequestBody MfflContract mfflContract) {
        mfflContractDao.update(mfflContract);
        return mfflContract;
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public void delete(@PathVariable Long id) {
        mfflContractDao.delete(id);
    }*/

}
